package com.market.cash.ui.presenter

import com.market.cash.configs.CashRootConfigs
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.view.ICashRootRepayView
import com.market.cash.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/25 11:59
 * @Annotation：待还款 Presenter 实现
 */
class CashRootRepayPresenter(private val iView: ICashRootRepayView): ProPresenter(iView) {

    private val CASHROOT_TYPE_GRADE = "TYPE_GRADE"//等级
    private val CASHROOT_TYPE_PAYMENT_TIPS = "TYPE_PAYMENT_TIPS"//还款提示
    private val CASHROOT_TYPE_ORDER = "TYPE_ORDER"//订单
    private val CASHROOT_TYPE_EMPTY = "TYPE_EMPTY"//空提示

    //选择的订单
    private var selectOrder: JSONObject? = null
    //订单详情列表
    private val detailsMap = HashMap<String,String>()

    /**
     * 加载待还款订单表
     */
    fun loadCashRootOrderListAction(){
        val orderList = ArrayList<JSONObject>()
        //用户等级item
        orderList.add(getCashRootGradeItem())

        //还款提示
        orderList.add(getCashRootPaymentTipsItem())

        //待还款订单列表
        val list = getCashRootOrderList()
        if (list != null && list.size > 0){
            orderList.addAll(list)
        } else {
            orderList.add(getCashRootEmptyItem())
        }
        iView.showCashRootOrderList(orderList)
    }

    /**
     * 获取用户等级
     */
    private fun getCashRootGradeItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",CASHROOT_TYPE_GRADE)
        item.put("grade",SharedHelper.getCashRootSPInt(SharedHelper.CashRoot_SPKEY.CASHROOT_VIP))
        return item
    }

    /**
     * 获取还款提示
     */
    private fun getCashRootPaymentTipsItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",CASHROOT_TYPE_PAYMENT_TIPS)
        return item
    }

    /**
     * 没有待还款订单
     */
    private fun getCashRootEmptyItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",CASHROOT_TYPE_EMPTY)
        return item
    }

    /**
     * 待还款订单列表
     */
    private fun getCashRootOrderList(): ArrayList<JSONObject>?{
        val pData = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_PRODUCT)
        if (pData.isNotEmpty()){
            val pList = arrayListOf<JSONObject>()
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                //待还款
                if (status == "REPAYMENT"){
                    item.put("itemType",CASHROOT_TYPE_ORDER)
                    item.put("isOpen",false)
                    pList.add(item)
                }
            }
            return pList
        }
        return null
    }

    /**
     * 设置点击的订单
     */
    fun setCashRootSelectOrder(order: JSONObject){
        this.selectOrder = order
    }

    /**
     * 切换展开或收起明细
     */
    fun checkCashRootOpenOrClose(){
        val position = selectOrder!!.optInt("index")
        //已展开 - 收起
        if (selectOrder!!.optBoolean("isOpen",false)){
            selectOrder!!.put("isOpen",false)
            iView.notifyCashRootItem(position)
            return
        }

        //是否已经存在详情列表 - 展开
        if (selectOrder!!.has("loadDetails")){
            selectOrder!!.put("isOpen",true)
            iView.notifyCashRootItem(position)
            return
        }

        //缓存里是否有订单详情
        val pName = selectOrder!!.optString("product")
        if (detailsMap.containsKey(pName)){
            selectOrder!!.put("isOpen",true)
            selectOrder!!.put("loadDetails",detailsMap[pName])
            iView.notifyCashRootItem(position)
            return
        }

        //未展开 && 没有详情
        loadCashRootRepayInfoAction()
    }

    /**
     * 获取还款信息
     */
    private fun loadCashRootRepayInfoAction(){
        val pName = selectOrder!!.optString("product")
        val pToken = selectOrder!!.optString("token")

        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_LOAN_REPAYMENT_INFO_PATH)
            put("product",pName)
            put("token",pToken)
        }
        doCashRootPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    detailsMap[pName] = obj.toString()
                    selectOrder!!.put("isOpen",true)
                    selectOrder!!.put("loadDetails",obj)
                    iView.notifyCashRootItem(selectOrder!!.optInt("index"))
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 订单还款
     */
    fun loadCashRootPayLinkAction(){
        iView.showCashRootLoading()
        val pName = selectOrder!!.optString("product")
        val pToken = selectOrder!!.optString("token")

        val params = JSONObject().addCommonParams().apply {
            put("product",pName)
            put("token",pToken)
            put("mobile",SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_MOBILE))
            put("path",ApiService.API_PATH.CASHROOT_API_LOAN_REPAYMENT_URL_PATH)
        }
        if (CashRootConfigs.isUgx() || CashRootConfigs.isKsh()){//肯尼亚、乌干达 需要使用 getOrderRepayH5 获取链接
            params.put("path",ApiService.API_PATH.CASHROOT_API_LOAN_REPAYMENT_KSH_UGX_URL_PATH)
        }

        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        doCashRootPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                iView.hideCashRootLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = ""
                    val url = obj.optString("url")
                    if (url.isNotEmpty()){
                        linkUrl = url
                    }

                    val repayUrl = obj.optString("repayUrl")
                    if (repayUrl.isNotEmpty()){
                        linkUrl = repayUrl
                    }

                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        iView.showCashRootPaymentStatusPage(pName,pToken,thirdOrderId)
                    } else {
                        iView.showCashRootPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }
}